//获取应用实例
const apikey = "dZcn2Vn5AXHpcPON2604FVia7wk="   
const app = getApp()

Page({
  data: {
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isHide: true,
    userdata:null,
// 扫描二维码的模块
    AuthorizationValue: "",
    userId: "",
    deviceId: "",
    deviceKey: "",
    productId: "",
    productKey: "",
// ↑
  },
  onLoad: function () {
    //有缓存我们就用缓存，没有缓存就用“绑定设备的”扫描二维码

    //获取设备ID的缓存
    var deviceIdStorage = wx.getStorageSync('deviceId')
    //获取产品ID的缓存
    var productIdStorage = wx.getStorageSync('productId')
    //获取AuthorizationValue的缓存
    var AuthorizationValueStorage = wx.getStorageSync('AuthorizationValue')
    this.setData({
      deviceId: deviceIdStorage,
      productId: productIdStorage,
      AuthorizationValue: AuthorizationValueStorage
    })

    //有缓存就检查设备是否在线
    if (this.data.deviceId != "" && this.data.AuthorizationValue != "" && this.data.productId != "")
      this.IsOnline();
  },

  
  onShow: function () {
    this.userdata = wx.getStorageSync("userInfo")
    var that = this;
    if (!that.userdata) {
      // 查看是否授权
      wx.getSetting({
        success: function (res) {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: function (res) {
                // 用户已经授权过,不需要显示授权页面,所以不需要改变 isHide 的值
                // 根据自己的需求有其他操作再补充
                // 我这里实现的是在用户授权成功后，调用微信的 wx.login 接口，从而获取code
                wx.login({
                  success: res => {
                    // 获取到用户的 code 之后：res.code
                    // 可以传给后台，再经过解析获取用户的 openid
                    // 或者可以直接使用微信的提供的接口直接获取 openid ，方法如下：
                    wx.request({
                      //     // 自行补上自己的 APPID 和 SECRET
                      url: 'https://api.weixin.qq.com/sns/jscode2session?appid=	wxb972ca011aec10e4&secret=ad8162c5c6362687901331bd6dc2c9b7&js_code=' + res.code + '&grant_type=authorization_code',
                      success: res => {
                        // 获取到用户的 openid
                        wx.setStorageSync("userInfo",res.data)
                      }
                    });
                  }
                });
              }
            });
          } else {
            // 用户没有授权
            // 改变 isHide 的值，显示授权页面
            that.setData({
              isHide: true
            });
          }
        }
      });
    } else {
      // console.log('11111')
      that.setData({
        isHide: false
      });
    }
  },
  //授权后跳入登录界面
  bindGetUserInfo: function (e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      // 获取到用户的信息了，打印到控制台上看下
      //授权成功后,通过改变 isHide 的值，让实现页面显示出来，把授权页面隐藏起来
      that.setData({
        isHide: false
      });
      wx.reLaunch({
        url: '../SignIn/SignIn'
      })

    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          // 用户没有授权成功，不需要改变 isHide 的值
          if (res.confirm) {
            console.log('用户点击了“返回授权”');
          }
        }
      });
    }
  },
  
  ConnectDevice: function () { //连接设备功能
    var that = this
    wx.showModal({
      title: '绑定设备',
      content: '请扫描设备后面的方形二维码',
      success: function (res) {
        if (res.confirm) {
          that.scanCode()
        }
      }
    })
  },
  scanCode: function () {  //扫描二维码
    var that = this
    wx.scanCode({ //扫描API
    }).then(res => {
      console.log("扫描成功,date:", res)
      //截取字符串
      var str = res.result

      //截取用户Id
      var leng = str.length
      var index = str.lastIndexOf("&");
      that.setData({
        userId: str.substring(index + 1, leng)
      })
      that.SetCache('userId', str.substring(index + 1, leng))
      str = str.substring(0, index);
      //截取产品码
      leng = index
      index = str.lastIndexOf("&");
      that.setData({
        productKey: str.substring(index + 1, leng)
      })
      that.SetCache('productKey', str.substring(index + 1, leng))
      str = str.substring(0, index);
      //截取产品Id
      leng = index
      index = str.lastIndexOf("&");
      that.setData({
        productId: str.substring(index + 1, leng)
      })
      that.SetCache('productId', str.substring(index + 1, leng))
      str = str.substring(0, index);
      //截取设备码
      leng = index
      index = str.lastIndexOf("&");
      that.setData({
        deviceKey: str.substring(index + 1, leng)
      })
      that.SetCache('deviceKey', str.substring(index + 1, leng))
      str = str.substring(0, index);
      //截取设备Id
      leng = index
      index = str.lastIndexOf("&");
      that.setData({
        deviceId: str.substring(index + 1, leng)
      })
      that.SetCache('deviceId', str.substring(index + 1, leng))
      //获取uthorizationValue

      //重服务器获取Authorization
      wx.request({
        url: 'http://ypbitx.natappfree.cc/MyServlet/getAuthorization',
        data: {
          resourceName: 'products/' + that.data.productId,
          accessKey: that.data.productKey
        },
        header: {
          'content-type': 'application/json'
        },
        success(res) {
          console.log("返回的AuthorizationValue" + res.data)
          that.setData({ AuthorizationValue: res.data })
          that.SetCache('AuthorizationValue', res.data)
          that.IsOnline()
        }
      })

      wx.showToast({
        title: '设备连接成功',
        duration: 2000
      })
    })

  },
  IsOnline: function () {
    var that = this
    if (that.data.deviceId != "" && that.data.AuthorizationValue != "" && this.data.productId) {
      wx.request({
        url: 'https://api.heclouds.com/devices/' + that.data.deviceId,
        data: {
          resourceName: 'products/' + that.data.productId,
          accessKey: that.data.productKey
        },
        header: {
          'content-type': 'application/json',
          'Authorization': that.data.AuthorizationValue
        },
        success(res) {
          console.log("IsOnline成功", res.data.data.online)
          if (res.data.data.online == true) {
            console.log("在线状态");
            //先设置图片为在线状态
            that.setData({
              Device_status: "../Image/Device_online.png"
            })
            // //存入缓存
            // that.SetCache('IsOnline',true)
            return true
          } else {
            console.log("离线状态")
            //先设置图片为离线状态
            that.setData({
              Device_status: "../Image/Device_offline.png"
            })
            //存入缓存
            // that.SetCache('IsOnline',false)
            return false
          }
        },
        fail(res) {
          console.log("IsOnline失败", res.data)
        }
      })
    } else {
      console.log("IsOnile参数为空")
    }
    return false;
  },
  SetCache: function (key, value) {
    wx.setStorage({
      key: key,
      data: value
    })
  },

})
